
############################ Lower resolution to higher resolution conversion ######################################
# Some images in .../FXTAS/CORRECTED/ntrimouse direction are NOT the highest resolution versions, contrary to what
# I had believed. I did have high resolution images stored in .../FXTAS/mouse/ntrimouse, but these images are 
# in Analyze format and had wrong World Coordinates. I need to combine the the correct World Coordinates in the 
# low resolution image from .../FXTAS/CORRECTED/ntrimouse and the high resolution data from .../FXTAS/mouse/ntrimouse
# to recreate the high resolution image.
#####################################################################################################################

def reconstruct_high_resolution_image(high_resolution_image_path_name,low_resolution_image_path_name,new_image_path_name):
    '''
    Input: 
        high_resolution_image_path_name: full path name of the high resolution image file 
        low_resolution_image_path_name: full path name of the low resolution image file 
        new_image_path_name: full path name of the new image file 
    '''
    import nibabel
    import os
    
    high_resolution_image_path_name=os.path.expanduser(high_resolution_image_path_name)
    low_resolution_image_path_name=os.path.expanduser(low_resolution_image_path_name)
    new_image_path_name=os.path.expanduser(new_image_path_name)

    high_image=nibabel.load(high_resolution_image_path_name)  
    high_shape=high_image.get_shape()
    low_image=nibabel.load(low_resolution_image_path_name)
    low_shape=low_image.get_shape()
    new_image_data=high_image.get_data()
    low_affine=low_image.get_affine()
    new_image_hdr=low_image.get_header().copy()

    # What kind of resolution differences do we have? I am dealing with only one kind now.
    if (high_shape[0]==low_shape[0]) and (high_shape[1]==low_shape[1]) and (high_shape[2]==2*low_shape[2]):
        new_affine=low_affine.copy()
        new_affine[range(4),2]=new_affine[range(4),2]/2
        # set the end_slice
        new_image_hdr["slice_end"]=high_shape[2]-1
    elif (high_shape[0]==2*low_shape[0]) and (high_shape[1]==2*low_shape[1]) and (high_shape[2]==low_shape[2]): 
        new_affine=low_affine.copy()
        new_affine[range(4),0]=new_affine[range(4),0]/2
        new_affine[range(4),1]=new_affine[range(4),1]/2
    elif (high_shape[0]==512) and (high_shape[1]==512) and (high_shape[2]==85): # special case
        new_affine=low_affine.copy()
        new_affine[range(4),2]=new_affine[range(4),2]/2
        # set the end_slice
        new_image_hdr["slice_end"]=84
    else:
        raise Exception("I have not learned how to deal with this.") 

    new_image=nibabel.Nifti1Image(new_image_data, affine=new_affine, header=new_image_hdr)
    new_image.to_filename(new_image_path_name)
